<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue'
import {
  getUserData,
  addOrUpdateUser,
  remove,
  getRole,
  setRole,
  someRemove,
} from '@/api/acl/user/index.ts'
import { ElMessage } from 'element-plus'
import useStoreSetting from '@/store/modules/setting.ts'
const useSetting = useStoreSetting()
let currentPage = ref(1)
let pageSize = ref(5)
let total = ref()
const userData = ref()
const drawer = ref(false)
const roleDrawer = ref(false)
const userParams = reactive<any>({
  name: '',
  username: '',
  password: '',
})
const ruleFormRef = ref()
const checkAll = ref(false)
const isIndeterminate = ref(false)
const allRole = ref<any>([])
const userRole = ref<any>([])
const selectIdArr = ref([])
const searchValue = ref('')
onMounted(() => {
  getUser()
})
const getUser = async (pager = 1) => {
  currentPage.value = pager
  let res = await getUserData(
    currentPage.value,
    pageSize.value,
    searchValue.value,
  )
  if (res.code === 200) {
    userData.value = res.data.records
    total.value = res.data.total
  }
}
const handleSizeChange = () => {
  getUser()
}
const addUser = () => {
  drawer.value = true
  Object.assign(userParams, {
    id: 0,
    name: '',
    username: '',
    password: '',
  })
  nextTick(() => {
    ruleFormRef.value.clearValidate('username')
    ruleFormRef.value.clearValidate('name')
    ruleFormRef.value.clearValidate('password')
  })
}
const editUser = (row: any) => {
  drawer.value = true
  Object.assign(userParams, row)
  nextTick(() => {
    ruleFormRef.value.clearValidate('username')
    ruleFormRef.value.clearValidate('name')
  })
}
const cancelClick = () => {
  drawer.value = false
  roleDrawer.value = false
}
const save = async () => {
  await ruleFormRef.value.validate()
  let res = await addOrUpdateUser(userParams)
  if (res.code === 200) {
    drawer.value = false
    ElMessage({
      type: 'success',
      message: userParams.id ? '更新成功' : '添加成功',
    })
    window.location.reload()
  } else {
    drawer.value = false
    ElMessage({
      type: 'error',
      message: userParams.id ? '更新失败' : '添加失败',
    })
  }
}
const deleteUserById = async (id: number) => {
  let res = await remove(id)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    await getUser(
      userData.value.length > 1 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
const verify = async () => {
  let data = {
    userId: userParams.id,
    roleIdList: userRole.value.map((item: any) => item.id),
  }
  let res: any = await setRole(data)
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '分配角色成功',
    })
    roleDrawer.value = false
    await getUser(currentPage.value)
  } else {
    ElMessage({
      type: 'error',
      message: '分配角色失败',
    })
  }
}
const assignRoles = async (row: any) => {
  Object.assign(userParams, row)
  let res: any = await getRole(row.id)
  if (res.code === 200) {
    allRole.value = res.data.allRolesList
    userRole.value = res.data.assignRoles
    roleDrawer.value = true
  }
}
const validatorUsername = (_: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户名字至少五位'))
  }
}
const validatorname = (_: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户昵称至少五位'))
  }
}
const validatorPassword = (_: any, value: any, callBack: any) => {
  if (value.trim().length >= 6) {
    callBack()
  } else {
    callBack(new Error('用户密码至少六位'))
  }
}
const rules = {
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  name: [{ required: true, trigger: 'blur', validator: validatorname }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}
const handleCheckAllChange = (val: any) => {
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: any) => {
  checkAll.value = value == allRole.value.length
  isIndeterminate.value = value !== allRole.value.length
}
const handleSelectionChange = (val: any) => {
  selectIdArr.value = val
}
const someDelete = async () => {
  let idList = selectIdArr.value.map((item: any) => {
    return item.id
  })
  let res = await someRemove(idList)
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    await getUser(
      userData.value.length > 1 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
const search = () => {
  getUser()
  searchValue.value = ''
}
const reset = () => {
  useSetting.refresh = !useSetting.refresh
}
</script>

<template>
  <el-card style="height: 70px; margin-bottom: 10px">
    <el-form class="form">
      <el-form-item label="用户名:">
        <el-input placeholder="请输入用户名" v-model="searchValue"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          plain
          @click="search"
          :disabled="!searchValue"
        >
          搜索
        </el-button>
        <el-button plain @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-button type="success" plain @click="addUser" v-has="`btn.User.add`">
      添加
    </el-button>
    <el-button
      type="danger"
      plain
      @click="someDelete"
      :disabled="!selectIdArr.length"
      v-has="`btn.User.AllDelete`"
    >
      批量删除
    </el-button>
    <el-table
      border
      style="margin: 10px 0"
      :data="userData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column type="index" label="#" align="center"></el-table-column>
      <el-table-column
        label="用户名字"
        align="center"
        prop="username"
      ></el-table-column>
      <el-table-column
        label="用户名称"
        align="center"
        prop="name"
      ></el-table-column>
      <el-table-column
        label="用户角色"
        align="center"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="350px" align="center">
        <template #="{ row }">
          <el-button
            type="primary"
            plain
            icon="User"
            @click="assignRoles(row)"
            v-has="`btn.User.assgin`"
          >
            分配角色
          </el-button>
          <el-button
            type="warning"
            plain
            icon="Edit"
            @click="editUser(row)"
            v-has="`btn.User.update`"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`你确定删除'${row.username}'吗？`"
            @confirm="deleteUserById(row.id)"
            width="250"
          >
            <template #reference>
              <el-button
                type="danger"
                plain
                icon="Delete"
                v-has="`btn.User.remove`"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15]"
      layout="prev, pager, next, jumper,->,total, sizes"
      :total="Number(total)"
      @size-change="handleSizeChange"
      @current-change="getUser"
      :pager-count="7"
    />

    <el-drawer v-model="drawer">
      <template #header>
        <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
      </template>
      <template #default>
        <el-form ref="ruleFormRef" :model="userParams" :rules="rules">
          <el-form-item label="用户名字" prop="username">
            <el-input
              placeholder="请输入用户名字"
              v-model="userParams.username"
              prop="username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户名称" prop="name">
            <el-input
              placeholder="请输入用户名称"
              v-model="userParams.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="!userParams.id">
            <el-input
              placeholder="请输入密码"
              v-model="userParams.password"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-drawer>
    <el-drawer v-model="roleDrawer">
      <template #header>
        <h4>分配角色(职位)</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input v-model="userParams.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="职位列表">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              v-model="userRole"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox v-for="item in allRole" :key="item.id" :label="item">
                {{ item.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="verify">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>

<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
